package com.example.demo.service;

import com.example.demo.drools.base.CheckResult;
import com.example.demo.drools.base.Result;
import com.example.demo.drools.base.RuleSchema;
import com.example.demo.rule.executor.CardReceiveExecutor;
import com.example.demo.rule.fact.CardReceiveFact;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class DemoService {

    @Autowired
    private CardReceiveExecutor cardReceiveExecutor;


    public Result test(Integer currentReceivedNum) {
        //正常流程是要先检验参数传入参数，再根据参数查询相关信息，比如用户的当前领取数量

        //规则事实
        CardReceiveFact fact = new CardReceiveFact();
		fact.setMaxReceiveNumber(currentReceivedNum + 1);

        //根据参数查询数据库获取规则模式编码和规则脚本，此处为了更直观的演示就没有连数据库了，直接硬编码写死这两个变量
        //规则模式编码
        String schemaCode = "W8V32BE36Q";
        //规则脚本
        String ruleScript = "package com.example.demo.rule.card.receive" +
                "\n" +
                "import org.slf4j.Logger;" +
                "import com.example.demo.drools.base.CheckResult;" +
                "import com.example.demo.rule.fact.CardReceiveFact;" +
                "\n" +
                "global Logger log;" +
                "global CheckResult result;" +
                "rule \"W8V32BE36Q_1082913542028271999\"" +
                "   no-loop true" +
                "   lock-on-active true" +
                "   salience 1000" +
                "   when" +
                "       fact : com.example.demo.rule.fact.CardReceiveFact(getMaxReceiveNumber() !=null && getMaxReceiveNumber() <=2);" +
                "   then" +
                "       result.setCode('200');" +
                "       result.setMessage('匹配成功');" +
                "       log.info('match success');" +
                "       update(fact);" +
                "end";

        //执行规则脚本
        CheckResult result = cardReceiveExecutor.excute(new RuleSchema(schemaCode, ruleScript), fact);
        return result.transf();
    }
}
